import { ref, onMounted, createVNode } from 'vue';
import { api } from '@/global/utils/api';
import useApiResultHandler from './api-promise-handler';
import { message } from 'ant-design-vue';
import 'ant-design-vue/es/message/style/css';
import { Modal } from 'ant-design-vue';
import CreateDepartmentModal from '@components/public/CreateDepartmentModal.vue';


export default function useDepartmentTable(t) {

  const loading = ref(false);
  const data = ref([]);
  const errorHandler = (err) => message.error(`请求出错：${err}`);

  const fetchTableData = () => {
    loading.value = true;
    useApiResultHandler(t,
      api.get("/department/getDepartment"),
      (result) => {
        data.value = result.data;
      },
      errorHandler,
      () => loading.value = false
    );
  }
  onMounted(() => {
    fetchTableData();
  });

  const toggleDepartmentState = (department) => {
    const copy = JSON.parse(JSON.stringify(department));
    copy.state = copy.state == 'OK' ? 'CLOSED' : 'OK';

    useApiResultHandler(t,
      api.post("/department/modifyDepartment", copy),
      (result) => {
        message.success("成功");
      },
      errorHandler,
      fetchTableData
    );
  };

  const openCreateDepartmentModal = () => {
    Modal.confirm({
      title: t('operations.createDepartment'),
      content: createVNode(CreateDepartmentModal)
    })
  }

  const columns = [
    {
      title: t('table.department.name'),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: t('table.department.state'),
      dataIndex: 'state',
      key: 'state',
    },
    {
      title: t('table.department.createTime'),
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: t('table.department.note'),
      dataIndex: 'note',
      key: 'note',
    },
    {
      title: t('table.action'),
      dataIndex: 'action',
      key: 'action',
    },
  ];

  return { columns, data, loading, toggleDepartmentState, openCreateDepartmentModal };
}